package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @projectName: heima-leadnews
 * @package: com.heima.app.gateway.filter
 * @className: AuthorizeFilter
 * @author: ZhouAo
 * @description: TODO
 * @date: 2022/6/11 21:04
 * @version: 1.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        //获取响应题
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        URI uri = request.getURI();
        //获取绝对路径
        String path = uri.getPath();
        //如果路径为登陆则直接放行
        if (path.contains("login_auth")) {
            return chain.filter(exchange);
        }
        //其它路径则查看是否有令牌
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        //获取令牌
        String token = headers.getFirst("token");
        //如果令牌为空则拦截
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果存在令牌则判断此令牌是否过期
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == 1 || i == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //未过期放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
